package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 消息的生产者
 */
public class ProducerQuickStart {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //kafka配置
        Properties properties = new Properties();
        //链接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        //序列化  key  value
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");

        //消息确认设置
        properties.put(ProducerConfig.ACKS_CONFIG,"all");

        //重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,10);

        //数据压缩
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"lz4");

        //创建生产者对象
        KafkaProducer<String,String> producer = new KafkaProducer<String, String>(properties);

        for (int i = 0; i < 5; i++) {
            //封装消息
            ProducerRecord<String,String> record = new ProducerRecord<String,String>("itcast-input-topic","key-02","hello kafka");
            //发送消息
            //同步发送
            RecordMetadata recordMetadata = producer.send(record).get();
            System.out.println(recordMetadata.partition());
        }


        //异步发送消息
        /*producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if(e!=null){
                    e.printStackTrace();
                }
                System.out.println(recordMetadata.partition());
            }
        });*/

        //关闭消息通道
        producer.close();
    }
}
